package com.leif.okhttp;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;


public class MainActivity extends ActionBarActivity {

    private OkHttpClient client = new OkHttpClient();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btnGet).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doGet("http://www.baidu.com");
            }
        });


        findViewById(R.id.btnPost).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPost();
            }
        });
    }


    private void doGet(final String url) {
        new Thread() {
            @Override
            public void run() {
                try {
                    String response = getResponse(url);
                    System.out.println(response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private String getResponse(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Log.e("Leif","start");
        Response response = client.newCall(request).execute();
        Log.e("Leif","end");
        String result = new String(response.body().bytes());
        System.out.println("result " + result);
        return response.body().toString();

    }


    private void doPost() {

    }

}
